import React, { useEffect, useRef, useCallback, useState } from 'react';
import { Input, Row, Col } from 'antd';
import { connect } from 'umi';
import MyStreamRTC from '@/components/WebRTC/MyStreamRTC';
import styles from './index.less';

const { Search } = Input;

const Index = ({ user }) => {
  const rtc = useRef(null);
  const localStream = useRef();
  // 数据存储变量
  const streams = useRef([]);
  const [users, setUsers] = useState([]);
  // Dom元素变量
  const itemRefs = useRef({});

  // 仅在挂载时触发
  useEffect(() => {
    return () => {
      if (rtc.current) {
        rtc.current.dispose();
      }
    };
  }, []);

  useEffect(() => {
    if (user) {
      const streamRtc = new MyStreamRTC(
        `${process.env.API}/rtcHub`,
        (name, stream) => {
          if (name !== user.userName) {
            // 建立通信的其它人加入集合
            if (streams.current.indexOf(name) < 0) {
              streams.current.push(name);
              setUsers([...streams.current]);
            }

            const video = itemRefs.current[name];
            if (video) {
              video.srcObject = stream;
            }
          } else {
            localStream.current.srcObject = stream;
          }
        },
      );
      streamRtc.setupSignalR().then(() => {
        streamRtc.login(user.userName);
      });
      rtc.current = streamRtc;
    }
  }, [user]);

  const callShip = useCallback(async (v) => {
    await rtc.current.call(v);
  }, []);

  return (
    <div className={styles.body}>
      <Search
        placeholder="输入用户名..."
        allowClear
        onSearch={callShip}
        enterButton="连接"
      />
      <p className={styles.bg}>
        <span>我</span>
        <video ref={localStream} autoPlay muted></video>
      </p>
      <Row gutter={16}>
        {users &&
          users.map((o, i) => {
            return (
              <Col span={12} key={i}>
                <div className={styles.li}>
                  <span>{o}</span>
                  <video
                    ref={(el) => (itemRefs.current[o] = el)}
                    autoPlay
                    muted
                  ></video>
                </div>
              </Col>
            );
          })}
      </Row>
    </div>
  );
};

const mapStateToProps = ({ global }) => ({
  user: global.user,
});

export default connect(mapStateToProps)(Index);
